//
//  GLTopScrollBarView.m
//  GLLibDemo
//
//  Created by huang long on 2017/6/28.
//  Copyright © 2017年 历山大亚. All rights reserved.
//

#import "GLScrollSegmentedBar.h"
#import "UIView+GL.h"
#import <Masonry/Masonry.h>
#import "UIImage+GL.h"

@interface GLScrollSegmentedBar ()

@property(nonatomic , weak)UILabel * selectedLabel;

@end

@implementation GLScrollSegmentedBar


- (instancetype)initWithArray:(NSArray *)titles{
    self = [super init];
    if (self) {
        //        NSLog(@"%@",ClassAndMethod);
        _badgeColor = [UIColor redColor];
        _titles = titles;
        [self setUI];
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        //        NSLog(@"%@",ClassAndMethod);
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _normalColor = [UIColor blackColor];
        _selectColor = [UIColor redColor];
        _titleFont = [UIFont systemFontOfSize:16];
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}


- (void)layoutSubviews{
    [super layoutSubviews];
    [self customLayoutFrame];
}

- (void)customLayoutFrame{
    if (self.titleButtons.count == 0) {
        return;
    }
    CGFloat x = 0;
    CGFloat height = self.frame.size.height;
    
    
    self.contentView.frame = self.bounds;
    for (int i = 0; i < self.titleButtons.count; i ++) {
        UIButton *button = self.titleButtons[i];
        
        NSString *title = self.titles[i];
        CGSize size = CGSizeMake(self.colWidth, height);
        if (self.colWidth == 0) {
            size = [title boundingRectWithSize:CGSizeMake(320, height) options:0 attributes:@{NSFontAttributeName:_titleFont} context:nil].size;
            if (self.minColWidth > 0 && size.width < self.minColWidth) {
                //如果最小的width存在就并且当前计算的size小于minColWidth 就重置size
                size = CGSizeMake(self.minColWidth, height);
            }else if (self.maxColWidth > self.minColWidth && size.width > self.maxColWidth){
                //如果最大的width存在就并且当前计算的size大于maxColWidth 就重置size
                size = CGSizeMake(self.maxColWidth, height);
            }
        }
        button.frame = CGRectMake(x + 20, 0, size.width+4, height);
        if (i == self.selectIndex) {
            _lineView.frame = CGRectMake(button.x - 10, height - 2, size.width + 20, 2);
        }
        x = CGRectGetMaxX(button.frame);
    }
    self.contentView.contentSize = CGSizeMake(x + 20, self.height);
}

- (void)setSelectIndex:(NSInteger)selectIndex{
    if (self.titleButtons.count == 0) {
        return;
    }
    if (selectIndex > self.titleButtons.count) {
        selectIndex = self.titleButtons.count - 1;
    }else if (selectIndex < 0){
        selectIndex = 0;
    }
    if (_selectIndex == selectIndex) {
        return;
    }
    UILabel *button = [self.titleButtons objectAtIndex:selectIndex];
    _selectIndex = selectIndex;
    //    [self buttonClick:button];
    if (self.didSelectedNewBlock) {
        self.didSelectedNewBlock(selectIndex,NO);
    }
    if (self.colWidth > 0) {
        self.selectedLabel = button;
    }
    [self chooseIndexLabel:button withCallBack:^(BOOL finish) {
        self.selectedLabel = button;
        if (self.didSelectedBlock){
            self.didSelectedBlock(selectIndex);
        }
    }];
}

- (void)setUI{
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    _titleButtons = [NSMutableArray array];
    for (int i = 0; i < self.titles.count; i ++) {
        UILabel *button = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        button.text = _titles[i];
        button.userInteractionEnabled = YES;
        button.font = _titleFont;
        button.textColor = _normalColor;
        button.textAlignment = NSTextAlignmentCenter;
        [button addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap:)]];
        [self.contentView addSubview:button];
        [_titleButtons addObject:button];
    }
    UIView *view = [[UIView alloc] init];
    [self.contentView addSubview:view];
    view.backgroundColor = [UIColor whiteColor];
    _lineView = view;
    
    
    [self buttonClick:[self.titleButtons firstObject]];
    
    //    [self setNeedsLayout];
}

#pragma mark - click
- (IBAction)buttonClick:(UILabel *)sender{
    if (sender == nil) {
        return;
    }
    NSInteger index = [self.titleButtons indexOfObject:sender];
    _selectIndex = index;
    if (self.didSelectedNewBlock) {
        self.didSelectedNewBlock(index,YES);
    }
    if (self.colWidth > 0) {
        self.selectedLabel = sender;
    }
    [self chooseIndexLabel:sender withCallBack:^(BOOL finish) {
        self.selectedLabel = sender;
        if (self.didSelectedBlock){
            self.didSelectedBlock(index);
        }
    }];
}


- (void)chooseIndexLabel:(UILabel *)label withCallBack:(void(^)(BOOL))callBack{
    if (label == nil) {
        return;
    }
    //    NSInteger index = [self.titleButtons indexOfObject:label];
    NSTimeInterval time = 0.25;
    if (_lineView.x == label.x - 10) {
        CGFloat height = self.height;
        //        _lineView.frame = CGRectMake(_lineView.width * (self.selectIndex), height - 4, _lineView.width, 4);
        _lineView.frame = CGRectMake(label.x - 10, height - 2, label.width + 20, 2);
        if (self.contentView.contentSize.width > self.contentView.width) {
            CGFloat x = label.centerX - _contentView.width * 0.5;
            if (x <= 0) {
                _contentView.contentOffset = CGPointMake(0, 0);
            }else if (x >= self.contentView.contentSize.width - self.contentView.width){
                _contentView.contentOffset = CGPointMake(self.contentView.contentSize.width - self.contentView.width, 0);
            }else{
                CGFloat cha = _contentView.contentOffset.x - x;
                if (cha > 32 || cha < - 32) {
                    _contentView.contentOffset = CGPointMake(x, 0);
                }
            }
        }
        if (callBack) {
            callBack(YES);
        }
        return;
    }
    [UIView animateWithDuration:time animations:^{
        CGFloat height = self.height;
        //        _lineView.frame = CGRectMake(_lineView.width * (self.selectIndex), height - 4, _lineView.width, 4);
        _lineView.frame = CGRectMake(label.x - 10, height - 2, label.width + 20, 2);
        if (self.contentView.contentSize.width > self.contentView.width) {
            CGFloat x = label.centerX - _contentView.width * 0.5;
            if (x <= 0) {
                _contentView.contentOffset = CGPointMake(0, 0);
            }else if (x >= self.contentView.contentSize.width - self.contentView.width){
                _contentView.contentOffset = CGPointMake(self.contentView.contentSize.width - self.contentView.width, 0);
            }else{
                CGFloat cha = _contentView.contentOffset.x - x;
                if (cha > 32 || cha < - 32) {
                    _contentView.contentOffset = CGPointMake(x, 0);
                }
            }
        }
    } completion:callBack];
}

- (IBAction)labelTap:(UIGestureRecognizer *)sender{
    UILabel *label = (UILabel *)sender.view;
    [self buttonClick:label];
}

#pragma mark - public
- (void)reloadData{
    [self setUI];
}

#pragma mark - setter

- (void)setSelectedLabel:(UILabel *)selectedLabel{
    _selectedLabel.textColor = _normalColor;
    _selectedLabel = selectedLabel;
    _selectedLabel.textColor = _selectColor;
}

- (void)setNormalColor:(UIColor *)normalColor{
    _normalColor = normalColor;
    for (UILabel * button in self.titleButtons) {
        if (button != _selectedLabel) {
            button.textColor = normalColor;
        }
    }
}

- (void)setSelectColor:(UIColor *)selectColor{
    _selectColor = selectColor;
    _selectedLabel.textColor = selectColor;
}

- (void)setTitleFont:(UIFont *)titleFont{
    _titleFont = titleFont;
    for (UILabel * button in self.titleButtons) {
        button.font = titleFont;
    }
}

#pragma mark - getter setter
- (UIScrollView *)contentView{
    if (_contentView == nil) {
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        scrollView.showsHorizontalScrollIndicator = NO;
        //        scrollView.autoresizesSubviews = NO;
        scrollView.contentInset = UIEdgeInsetsZero;
        [self addSubview:scrollView];
        _contentView = scrollView;
    }
    return  _contentView;
}


- (void)setRedBadgeHidden:(BOOL)hidden withIndex:(NSInteger)index{
    if (index >= self.titleButtons.count || index < 0) {
        return;//防止其他人传入索引有误
    }
    UIButton *button = [self.titleButtons objectAtIndex:index];
    UIImageView *imageView = [button viewWithTag:23];
    if (imageView) {
        if (hidden) {
            [imageView removeFromSuperview];
        }
    }else{
        if (!hidden) {
            imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 6, 6)];
            
            NSString *title = self.titles[index];
            CGSize size = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, self.height) options:0 attributes:@{NSFontAttributeName:self.titleFont} context:nil].size;
            
            imageView.image = [UIImage gl_badgeImageWithColor:self.badgeColor withSize:imageView.size];
            [button addSubview:imageView];
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.offset(size.width * 0.5 + 1);
                make.centerY.offset(-self.titleFont.pointSize * 0.5);
            }];
        }
    }
    
}

- (void)setColWidth:(CGFloat)colWidth{
    if (isnan(colWidth) || colWidth < 0) {
        colWidth = 0;
    }
    _colWidth = colWidth;
}

- (void)setMinColWidth:(CGFloat)minColWidth{
    if (isnan(minColWidth) || minColWidth < 0) {
        minColWidth = 0;
    }
    _minColWidth = minColWidth;
}

- (void)setMaxColWidth:(CGFloat)maxColWidth{
    if (isnan(maxColWidth) || maxColWidth < 0) {
        maxColWidth = 0;
    }
    _maxColWidth = maxColWidth;
}

@end


@implementation GLScrollAutoSegmentedBar

- (void)customLayoutFrame{
    if (self.titleButtons.count == 0) {
        return;
    }
    CGFloat height = self.frame.size.height;
    
    self.contentView.frame = self.bounds;
    NSMutableArray *widthArray = [NSMutableArray arrayWithCapacity:self.titleButtons.count];
    CGFloat contentSize = 20;
    for (int i = 0; i < self.titleButtons.count; i ++)  {
        NSString *title = self.titles[i];
        CGSize size = CGSizeMake(self.colWidth, height);
        if (self.colWidth == 0) {
            size = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, self.height) options:0 attributes:@{NSFontAttributeName:self.titleFont} context:nil].size;
            if (self.minColWidth > 0 && size.width < self.minColWidth) {
                //如果最小的width存在就并且当前计算的size小于minColWidth 就重置size
                size = CGSizeMake(self.minColWidth, height);
            }else if (self.maxColWidth > self.minColWidth && size.width > self.maxColWidth){
                //如果最大的width存在就并且当前计算的size大于maxColWidth 就重置size
                size = CGSizeMake(self.maxColWidth, height);
            }
        }
        [widthArray addObject:@(size.width)];
        contentSize += 20 + size.width;
    }
    if (contentSize < self.contentView.width) {
        
        [self avgNumberArray:widthArray IndexArray:nil length:self.width - 20 * (self.titleButtons.count + 1)];
        
    }
    CGFloat x = 0;
    for (int i = 0; i < self.titleButtons.count; i ++) {
        UIButton *button = [self.titleButtons objectAtIndex:i];
        CGFloat tempWidth = ((NSNumber *)[widthArray objectAtIndex:i]).floatValue;
        button.frame = CGRectMake(x + 20, 0, tempWidth, self.height);
        if (i == self.selectIndex) {
            self.lineView.frame = CGRectMake(button.x - 10, height - 2, tempWidth + 20, 2);
        }
        x = CGRectGetMaxX(button.frame);
    }
    self.contentView.contentSize = CGSizeMake(x + 20, self.height);
}


- (void)avgNumberArray:(NSMutableArray *)numberArray IndexArray:(NSMutableArray *)indexArray length:(CGFloat)length{
    CGFloat width = 0;
    CGFloat maxWidth = 0; //最大的宽度
    NSMutableArray *tempArray = [NSMutableArray array];//最大宽度的索引数组
    for (NSInteger i = 0; i < numberArray.count; i ++) {
        if (![indexArray containsObject:@(i)]) {
            NSNumber *number = [numberArray objectAtIndex:i];
            width += number.floatValue;
            if (maxWidth < number.floatValue) {
                maxWidth = number.floatValue; //最大宽度 重新赋值
                tempArray = [NSMutableArray arrayWithObject:@(i)]; //索引数组
            }else if (maxWidth == number.floatValue){
                [tempArray addObject:@(i)];
            }
        }
    }
    if (length > width) {
        //做处理
        CGFloat avgWidth = length / (numberArray.count - indexArray.count);
        if (avgWidth <= maxWidth) {
            if (indexArray == nil) {
                indexArray = [NSMutableArray array];
            }
            [indexArray addObjectsFromArray:tempArray];
            [self avgNumberArray:numberArray IndexArray:indexArray length:length - tempArray.count * maxWidth];
        }else{
            for (NSInteger i = 0; i < numberArray.count; i ++) {
                if (![indexArray containsObject:@(i)]) {
                    //
                    [numberArray replaceObjectAtIndex:i withObject:@(avgWidth)];
                }
            }
        }
    }
}


@end
